<template>
  <view class="home-comm">
    <!-- https://z-paging.zxlee.cn/start/install.html -->
    <z-paging ref="paging" v-model="dataList" @query="queryList">
      <!-- 自定义下拉刷新view(如果use-custom-refresher为true且不设置下面的slot="refresher"，此时不用获取refresherStatus，会自动使用z-paging自带的下拉刷新view) -->

      <!-- 注意注意注意！！字节跳动小程序中自定义下拉刷新不支持slot-scope，将导致custom-refresher无法显示 -->
      <!-- 如果是字节跳动小程序，请参照sticky-demo.vue中的写法，此处使用slot-scope是为了减少data中无关变量声明，降低依赖 -->
      <template #refresher="{ refresherStatus }">
        <!-- 此处的custom-refresh为demo中自定义的组件，非z-paging的内置组件，请在实际项目中自行创建。这里插入什么view，下拉刷新就显示什么view -->
        <CustomRefresher :status="refresherStatus" />
      </template>
      <!-- 自定义加载更多view -->
      <template #loading>
        <!-- 此处的custom-full-loading为demo中自定义的组件，非z-paging的内置组件，请在实际项目中自行创建。这里插入什么view，没有更多数据就显示什么view -->
        <CustomFullLoading />
      </template>

      <!-- 自定义没有更多数据view -->
      <template #loadingMoreNoMore>
        <!-- 此处的custom-nomore为demo中自定义的组件，非z-paging的内置组件，请在实际项目中自行创建。这里插入什么view，没有更多数据就显示什么view -->
        <CustomNomore />
      </template>

      <!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
      <view class="card">
        <view class="cards-title">
          <view class="search-container">
            <view class="search-wrapper">
              <uv-search
                placeholder="搜索角色名称/关键词/标签"
                v-model="keyword"
                :show-action="false"
                @search="(e) => searchEvent('onSearch', e)"
                @clear="searchEvent('onClear')"
                @custom="searchEvent('onSearch', keyword)"
                :clearable="true"
                shape="round"
                bgColor="none"
                color="var(--text-primary)"
                :height="40"
                placeholderColor="var(--text-placeholder)"
                :inputStyle="{
                  color: 'var(--text-primary)',
                  fontSize: '28rpx',
                  padding: '0 24rpx',
                  borderRadius: '25px',
                  backgroundColor: 'none',
                }"
                :placeholderStyle="{
                  color: 'var(--text-placeholder)',
                  fontSize: '28rpx',
                  backgroundColor: 'none',
                }"
                :customStyle="{
                  boxShadow: '0 2px 12px rgba(0, 0, 0, 0.1)',
                  border: '1px solid var(--border-color)',
                  borderRadius: '25px',
                  margin: '20rpx 4rpx 20rpx 20rpx',
                  backgroundColor: 'none',
                }"
              >
                <!-- <template #action>
                  <view
                    class="search-btn"
                    :class="{ 'search-btn-show': !!keyword }"
                    @tap.stop="searchEvent('onSearch', keyword)"
                    hover-class="search-btn-hover"
                    :style="{
                      color: 'var(--color-primary)',
                      fontWeight: '500',
                      padding: '0 24rpx',
                    }"
                  >
                    搜索
                  </view>
                </template> -->
              </uv-search>
            </view>
            <view class="search-right">
              <view class="switch-item">
                <uv-switch
                  v-model="switchValue.switch1"
                  :space="0"
                  :size="15"
                  activeColor="var(--text-active-primary)"
                  inactiveColor="#808080"
                ></uv-switch>
                <view class="switch-label">开关开关</view>
              </view>
              <view class="switch-item">
                <uv-switch
                  v-model="switchValue.switch2"
                  :space="0"
                  :size="15"
                  activeColor="var(--text-active-primary)"
                  inactiveColor="#808080"
                ></uv-switch>
                <view class="switch-label">开关开关</view>
              </view>
            </view>
          </view>

          <uv-tabs
            :list="cardsList"
            @change="(e) => handerEvent('cardsListListChange', e)"
            :itemWidth="180"
            :scrollable="false"
            :activeStyle="{
              color: 'var(--text-active-primary)',
              fontWeight: '600',
              fontSize: '32rpx',
              transform: 'scale(1.1)',
              transition: 'all 0.3s ease',
            }"
            :inactiveStyle="{
              color: 'var(--text-regular)',
              fontSize: '28rpx',
              transform: 'scale(1)',
              transition: 'all 0.3s ease',
            }"
            lineColor="var(--text-active-primary)"
            lineWidth="30"
            lineHeight="2"
            itemStyle="padding-left: 15px; padding-right: 15px; height: 80rpx;"
          ></uv-tabs>

          <!-- <view
            class="cards-tag"
            v-if="targetCardsTag?.cardsTagList && targetCardsTag.cardsTagList.length > 0"
          >
            <view
              class="tags-item"
              v-for="(item, index) in targetCardsTag.cardsTagList"
              :key="index"
            >
              <view class="tags-item-name" v-if="item.allName">{{ item.allName }}:</view>
              <view class="tags-options">
                <view
                  v-for="(option, optionIndex) in item.option"
                  :key="optionIndex"
                  class="tag-option"
                  :class="{ 'tag-option-active': option.key === item.activeTagKey }"
                  @click="handleTagSelect(index, optionIndex)"
                >
                  {{ option.name }}
                </view>
              </view>
            </view>
          </view> -->
          <!-- <FilterDropdown /> -->
          <InfoTags :items="targetCardsTag"></InfoTags>
        </view>

        <view class="list-card">
          <!-- <view class="item" v-for="(item, index) in dataList" :key="index">
            <view class="serial-number">
              <view>
                {{ item.card_name }}
              </view>
            </view>
           
          </view> -->

          <CardItem
            v-for="(card, index) in dataList"
            :key="card.role_id"
            :data="card"
            @click="onCardClick"
          />
        </view>
      </view>
    </z-paging>
    <uv-toast ref="toastRef"></uv-toast>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { onShow, onLoad } from "@dcloudio/uni-app";
import request from "@/utils/zpagingrequest.js";
import CustomFullLoading from "../../TBMComponents/components/CustomFullLoading/index.vue";

import CustomNomore from "./components/CustomNomore/index.vue";
import CustomRefresher from "./components/CustomRefresher/index.vue";
// import FilterDropdown from "./components/FilterDropdown/index.vue";
import InfoTags from "./components/InfoTags/index.vue";
import RoleAPI from "@/api/system/role";
import CardItem from "../../TBMComponents/components/CardsItem/index.vue";

import {
  rankOptions,
  genderOptions,
  modeOptions,
  tagOptions,
  independentOptions,
  takeTurnOptions,
} from "./data";
import { useCardsStore } from "@/store/index";

const cardsStore = useCardsStore();
const paging = ref(null);
const toastRef = ref(null);
// v-model绑定的这个变量不要在分页请求结束中自己赋值，直接使用即可
const dataList = ref([]);

const loading = ref(true);
const keyword = ref("");
const switchValue = ref({
  switch1: true,
  switch2: false,
});

const props = defineProps();

const cardsList = ref([
  {
    name: "月榜",
    key: "yuebang",
    cardsTagValue: {
      2: "all",
      1: "11",
    },
    cardsTagList: [
      rankOptions,
      genderOptions,
      modeOptions,
      tagOptions,
      independentOptions,
      takeTurnOptions,
    ],
  },
  {
    name: "精选",
    key: "jingxuan",
    cardsTagList: [
      {
        id: 1,
        option: [
          {
            name: "全部",
            key: "all",
          },
          {
            name: "男性向",
            key: "112",
          },
          {
            name: "女性向",
            key: "114",
          },
        ],
      },
    ],
  },
  {
    name: "热门",
    key: "remen",
  },
  {
    name: "上新",
    key: "shangxin",
  },
  {
    name: "群组",
    key: "qunzu",
  },
]);
const targetCardsTag = ref(cardsList.value[0]);

// 处理标签选择
const handleTagSelect = (tagIndex, optionIndex) => {
  if (!targetCardsTag.value || !targetCardsTag.value.cardsTagList) return;

  const tagItem = targetCardsTag.value.cardsTagList[tagIndex];
  if (!tagItem || !tagItem.option) return;

  const selectedOption = tagItem.option[optionIndex];
  if (!selectedOption) return;

  // 更新选中的标签key
  tagItem.activeTagKey = selectedOption.key;

  console.log(
    `选中标签: ${tagItem.allName || "标签"} - ${selectedOption.name}, key: ${
      selectedOption.key
    }`
  );

  // 获取所有选中的标签
  const selectedTags = getSelectedTags();
  console.log("所有选中的标签:", selectedTags);

  // 这里可以添加选择标签后的其他逻辑，比如刷新列表数据
  paging.value.reload();
};

// 获取所有选中的标签
const getSelectedTags = () => {
  if (!targetCardsTag.value || !targetCardsTag.value.cardsTagList) return [];

  const selectedTags = [];

  targetCardsTag.value.cardsTagList.forEach((tagItem) => {
    if (tagItem.activeTagKey && tagItem.option) {
      const selectedOption = tagItem.option.find(
        (opt) => opt.key === tagItem.activeTagKey
      );
      if (selectedOption) {
        selectedTags.push({
          tagName: tagItem.allName || "标签",
          optionName: selectedOption.name,
          optionKey: selectedOption.key,
        });
      }
    }
  });

  return selectedTags;
};

// @query所绑定的方法不要自己调用！！需要刷新列表数据时，只需要调用paging.value.reload()即可
const queryList = async (pageNum, pageSize) => {
  // 组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
  // 这里的pageNo和pageSize会自动计算好，直接传给服务器即可
  // 模拟请求服务器获取分页数据，请替换成自己的网络请求

  // 模拟数据
  const params = {
    pageNo: pageNum,
    pageSize: pageSize,
    type: 1,
  };
  // request
  //   .queryList(params)
  //   .then((res) => {
  //     // 将请求的结果数组传递给z-paging
  //     console.log(
  //       "%c [ res.data.list ] 日志",
  //       "font-size:13px; background:#26A08F; color:#fff;",
  //       res.data.list
  //     );
  //     paging.value.complete(res.data.list);
  //   })
  //   .catch((res) => {
  //     // 如果请求失败写this.$refs.paging.complete(false);
  //     // 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
  //     // 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
  //     paging.value.complete(false);
  //   });

  const paramsList = {
    start: (pageNum - 1) * pageSize,
    size: pageSize,
    token: "123456789",
  };

  let paramsListRes = await RoleAPI.getList(paramsList);
  console.log(
    "%c getInit 角色列表 res2: ",
    "color: #1E90FF; font-weight: bold;",
    paramsListRes
  );
  console.log(
    "%c getInit paramsList2: ",
    "color: #1E90FF; font-weight: bold;",
    paramsList
  );
  paging.value.complete(paramsListRes.data);
};
const handerEvent = async (eType, eData) => {
  console.log("%c :handerEvent eType", "color: #1E90FF; font-weight: bold;", eType);
  console.log("%c :handerEvent eData", "color: #1E90FF; font-weight: bold;", eData);

  switch (eType) {
    case "cardsListListChange":
      // tabsListState.value.filter.status = eData?.key;
      // paging.value.reload();
      targetCardsTag.value = eData;

      // 初始化标签的activeTagKey
      if (
        targetCardsTag.value?.cardsTagList &&
        targetCardsTag.value.cardsTagList.length > 0
      ) {
        targetCardsTag.value.cardsTagList.forEach((tagItem) => {
          if (tagItem.option && tagItem.option.length > 0 && !tagItem.activeTagKey) {
            // 默认选中第一个选项
            tagItem.activeTagKey = tagItem.option[0].key;
          }
        });
      }

      break;

    default:
      break;
  }
};
const searchEvent = async (eType, eData) => {
  console.log("%c :searchEvent eType", "color: #1E90FF; font-weight: bold;", eType);
  console.log("%c :searchEvent eData", "color: #1E90FF; font-weight: bold;", eData);
  switch (eType) {
    case "onClear":
      keyword.value = "";
      break;
    case "onSearch": //搜索 跳转到 搜索列表
      if (keyword.value == "") {
        toastRef.value.show({
          message: "请输入搜索内容",
          duration: 2000,
        });
        return;
      }
      uni.navigateTo({
        url:
          "/pages/cards/componentsPages/cardsSearchList/index?keyword=" + keyword.value,
      });
      keyword.value = "";
      // uni.navigateTo({
      //   url: "pages/cards/componentsPages/cardsSearchList/index?keyword=" + keyword.value,
      // });
      // paging?.value?.reload();
      break;
    default:
      break;
  }
};
const onCardClick = (card) => {
  console.log("点击了卡片：", card);
  cardsStore.setCurrentCard(card);
  uni.navigateTo({
    url: "/pages/cardsDetail/index",
  });
};
onLoad((option) => {
  console.log(option, "==home=option====");
  paging?.value?.reload();
});

const getInit = async () => {
  console.log("getInit====home======");
};
// 点击列表的每一项
const itemClick = (item) => {
  console.log(item, "===item");
};

onShow(() => {
  console.log("show home");
  paging?.value?.reload();
});

// watch(() => props.pageData, () => {
// 	console.log( props,"===== props.pageData props.pageData");
// 	console.log( props.pageData.type,"===== type.type type.type");
// 	getInit()
// }, {
// 	immediate: true,
// 	deep: true
// })

onMounted(() => {
  console.log(props, "===== props.pageData props.pageData");
  getInit();
  // uni.showLoading({
  // 	title: "加载中",
  // 	mask: true
  // });
  // getInit()
  // console.log(props, "===props===props===");
  // setTimeout(() => {
  // 	uni.hideLoading()
  // }, 1500)

  // 初始化标签的activeTagKey
  if (
    targetCardsTag.value?.cardsTagList &&
    targetCardsTag.value.cardsTagList.length > 0
  ) {
    targetCardsTag.value.cardsTagList.forEach((tagItem) => {
      if (tagItem.option && tagItem.option.length > 0 && !tagItem.activeTagKey) {
        // 默认选中第一个选项
        tagItem.activeTagKey = tagItem.option[0].key;
      }
    });
  }
});
</script>

<style scoped lang="scss">
.home-comm {
  height: 100%;
  overflow: hidden;
  display: flex;
  width: 100%;
  flex-direction: column;
  align-items: center;

  .search-container {
    display: flex;
    .search-wrapper {
      width: 100%;

      .search-btn {
        padding: 0 15px;
        color: var(--text-active-primary);
        font-size: 28rpx;
        opacity: 0;
        transform: translateX(-20px);
        transition: all 0.3s ease;

        &-show {
          opacity: 1;
          transform: translateX(0);
        }
      }
    }
    .search-right {
      display: flex;
      flex-direction: column;
      align-items: start;
      justify-content: center;
      width: 230rpx;
      align-items: center;
      transform: scale(0.8);
      margin-bottom: 10rpx;
      gap: 8rpx;
      .switch-item {
        width: 100%;
        display: flex;
      }

      .switch-label {
        font-size: 24rpx;
        color: var(--text-regular);
        margin-left: 5rpx;
      }
    }
  }
  .card {
    height: 100%;
    width: 100%;
    .cards-tag {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      padding: 0 20rpx;
      margin-top: 20rpx;
      .tags-item {
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-right: 20rpx;
        margin-bottom: 20rpx;
        .tags-item-name {
          font-size: 24rpx;
          color: #666;
          margin-right: 10rpx;
          font-weight: 500;
        }
        .tags-options {
          display: flex;
          flex-direction: row;
          flex-wrap: wrap;
          .tag-option {
            padding: 4rpx 16rpx;
            background-color: #f5f5f5;
            border-radius: 20rpx;
            font-size: 24rpx;
            color: #666;
            margin-right: 10rpx;
            margin-bottom: 10rpx;
            transition: all 0.2s ease;
            &.tag-option-active {
              background-color: #007aff;
              color: #fff;
            }
            &:active {
              opacity: 0.8;
            }
          }
        }
      }
    }
    .list-card {
      // background-position: center center;
      margin-bottom: 50rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 0 24rpx;
      box-sizing: border-box;

      // 渐变边框 伪元素+透明边框
      //background: #fff;
      //border: 4rpx solid transparent;
      //background-clip: padding-box, border-box;
      //background-origin: padding-box, border-box;
      // background-image: linear-gradient(to right, #fff, #fff), linear-gradient(90deg, #8f41e9, #578aef);
      .item {
        width: 100%;
        height: 600rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
</style>
